<?php

namespace App\Http\Controllers;

use App\Library\R;
use App\Messages\VerificationCodeMessage;
use App\Models\SmsExtensiveTemplate;
use App\Traits\File;
use App\Traits\Msg;
use Illuminate\Http\Request;
use App\Models\SmsLog;
use Validator;

class PublicController extends Controller
{
    use Msg;
    use File;

    //图片上传处理
    public function uploadImg(Request $request)
    {
        $maxSize = 10; //上传文件最大大小,单位M
        $allowed_extensions = ["png", "jpg", "gif"];
        $file = $request->file('file');

        // 检查文件是否上传完成
        if ($file->isValid()) {
            // 检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $msg = "请上传" . implode(",", $allowed_extensions) . "格式的图片";
                return $this->error($msg);
            }
            // 检测图片大小
            if ($file->getClientSize() > $maxSize * 1024 * 1024) {
                $msg = "图片大小限制" . $maxSize . "M";
                return $this->error($msg);
            }

            // 上传
            $res = $this->uploadByBuf(file_get_contents($file->getRealPath()), $file->getClientOriginalExtension());
            $res = $res->original;

            if ($res['code'] == 0) {
                return $this->success('上传成功', [], $res['url']);
            }
            return $this->error('上传失败：' . $res['msg']);
        }
        return $this->error($file->getErrorMessage());
    }

    /**
     * @author  sql
     * 群发广泛模板 相同内容发送多人,并存入日志
     */
    public function sendMsgToMany(Request $request)
    {
        $phones = $request->post('phone', '');
        $msg = $request->post('msg');
        $uid = $request->post('uid');
        $sendsource = $request->post('sendsource', 1);
        $model = new  SmsExtensiveTemplate();
        $response = $model->sendBatch($phones, $msg);//内容相同

        //存入发送日志
        if ($response['code'] != '00000') {
            return $this->error('请求运营商接口失败');
        }
        $all_msg = $response['result'];
        $smsModel = new SmsLog();
        foreach ($all_msg as $i) {
            $smsModel->addLog($i['phone'], $msg, $i['status'], $i['desc'], 1, $uid, $sendsource);
        }
        return $this->success('发送成功');

    }

    /**
     * @author  sql
     * 群发广泛模板 一对一发送个性短信
     */
    public function sendMsgToDistict(Request $request)
    {
        $content = $request->post('content', []);
        $model = new  SmsExtensiveTemplate();
        $content = [['phone' => '18701605391', 'msg' => '【好汉科技】六时吉祥', 'extend' => '']];
        var_dump($model->sendDistinct($content));;//内容相同
    }

    /**
     * 获取验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVCode(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'mobile' => 'required|numeric|regex:/^1[3456789][0-9]{9}$/',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            $phone = $request->get('mobile');

            // 频率限制
            if ($this->getLastCodeTime($phone)) {
                return $this->error('请求过于频繁，请稍后再试');
            }

            $this->storeLastCodeTime($phone); // 记录最后请求时间

            $code = mt_rand(1000, 9999);
            $ret = $this->sendMsg($phone, new VerificationCodeMessage($code));
            // for testing purpose only
            //$this->sendMsg('15910261926', new VerificationCodeMessage($code));

            $ret = $ret->original;
            if ($ret['code'] === 0) {
                $this->storeMsgCode($phone, $code); // 记录验证码

                return $this->success('success', ['verification_code' => $code]);
            }

            return $this->error($ret['msg']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}